package com.tongfusoft.web.core.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.tongfusoft.web.core.service.ITreeService;

public abstract class JsonTreeBaseAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	
	//默认的key值
	private static final String KEY_ID = "id";
	private static final String KEY_NAME = "name";
	private static final String KEY_ISPARENT = "isParent";
	private static final String KEY_PARENT_ID = "pId";
	
	private ITreeService treeService;
	/**
	 * 传入的父节点id
	 */
	private String id;
	
	public ITreeService getTreeService() {
		return treeService;
	}

	public void setTreeService(ITreeService treeService) {
		this.treeService = treeService;
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * 获取ID的属性名
	 * @return
	 */
	public abstract String getIdAttrName();
	
	/**
	 * 获取Name的属性名
	 * @return
	 */
	public abstract String getNameAttrName();
	
	/**
	 * 是否包含子节点
	 * @param id
	 * @return
	 */
	public abstract boolean isParent(String id);
	
	/**
	 * 获取Root的名字
	 * @return
	 */
	public abstract String getRootName();
	
	
	/**
	 * 获取树的子节点，并组装成json
	 */
	public void getChildrenList(){
		List<Map<String,Object>> list = this.getTreeService().getChildrenNodeList(this.getId());
		if(list != null && list.size() > 0){
			List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
			for(Map<String,Object> map : list){
				
				map.put(KEY_ID, map.get(this.getIdAttrName()));
				map.put(KEY_NAME, map.get(this.getNameAttrName()));
				map.put(KEY_ISPARENT, this.isParent((String)map.get(KEY_ID)));
				map.put(KEY_PARENT_ID, this.getId());
				
				//获取其他需要的Name的属性名
				List<String> others = this.getOthersNameAttrName();
				if(others != null){
					for (String other : others) {
						map.put(other, map.get(other.toUpperCase()));
					}
				}
				result.add(map);
			}
			
			if(StringUtils.isEmpty(this.getId())){  //初次访问，增加一个根
				result.add(getRootNode());
			}
			
			super.outJson(result);
		}else{
			super.outString("[]");
		}
	}
	
	private Map<String,Object> getRootNode(){
		Map<String,Object> root = new HashMap<String,Object>();
		root.put("name", super.getText(this.getRootName()));
		root.put("id", this.getId());
		
		return root;
	}
	/**
	 * 获取其他需要的Name的属性名
	 * @return
	 */
	public List<String> getOthersNameAttrName(){
		return null;
	}
}
